<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>工序流转记录</span>
          <div>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <el-descriptions v-if="batchInfo.batchCode" title="批次信息" :column="3" border>
        <el-descriptions-item label="批次号">{{ batchInfo.batchCode }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ batchInfo.productName }}</el-descriptions-item>
        <el-descriptions-item label="计划数量">{{ batchInfo.plannedQuantity }}</el-descriptions-item>
        <el-descriptions-item label="批次状态">
          <el-tag :type="getBatchStatusType(batchInfo.status)">
            {{ getBatchStatusText(batchInfo.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="计划日期">{{ parseTime(batchInfo.plannedDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="实际日期">{{ batchInfo.actualDate ? parseTime(batchInfo.actualDate, '{y}-{m}-{d}') : '-' }}</el-descriptions-item>
      </el-descriptions>

      <el-divider />

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['qep:production:process:add']"
            v-if="['PLANNED', 'IN_PROGRESS'].includes(batchInfo.status)"
          >添加工序记录</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['qep:production:process:edit']"
            v-if="['PLANNED', 'IN_PROGRESS'].includes(batchInfo.status)"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['qep:production:process:remove']"
            v-if="['PLANNED', 'IN_PROGRESS'].includes(batchInfo.status)"
          >删除</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="flowList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="工序名称" align="center" prop="processName" />
        <el-table-column label="工序类型" align="center" prop="processType" />
        <el-table-column label="操作人员" align="center" prop="operator" />
        <el-table-column label="开始时间" align="center" prop="startTime" width="150">
          <template #default="scope">
            <span>{{ scope.row.startTime ? parseTime(scope.row.startTime) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="150">
          <template #default="scope">
            <span>{{ scope.row.endTime ? parseTime(scope.row.endTime) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="工序状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="getProcessStatusType(scope.row.status)">
              {{ getProcessStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="异常标记" align="center" prop="hasException" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.hasException" type="danger">异常</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button 
              link type="primary" 
              icon="View" 
              @click="handleView(scope.row)"
              v-hasPermi="['qep:production:process:query']"
            >查看</el-button>
            <el-button 
              link type="primary" 
              icon="Edit" 
              @click="handleUpdate(scope.row)" 
              v-hasPermi="['qep:production:process:edit']"
              v-if="scope.row.status !== 'COMPLETED' && ['PLANNED', 'IN_PROGRESS'].includes(batchInfo.status)"
            >修改</el-button>
            <el-button 
              link type="primary" 
              icon="Check" 
              @click="handleComplete(scope.row)" 
              v-hasPermi="['qep:production:process:edit']"
              v-if="scope.row.status === 'IN_PROGRESS'"
            >完成</el-button>
            <el-button 
              link type="primary" 
              icon="Warning" 
              @click="handleException(scope.row)" 
              v-hasPermi="['qep:production:process:edit']"
              v-if="scope.row.status === 'IN_PROGRESS'"
            >异常</el-button>
            <el-button 
              link type="primary" 
              icon="Delete" 
              @click="handleDelete(scope.row)" 
              v-hasPermi="['qep:production:process:remove']"
              v-if="scope.row.status === 'PENDING' && ['PLANNED', 'IN_PROGRESS'].includes(batchInfo.status)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改工序流转记录对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="flowForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchId">
              <el-input v-model="batchInfo.batchCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序" prop="processId">
              <el-select v-model="form.processId" placeholder="请选择工序" @change="handleProcessChange">
                <el-option
                  v-for="item in processOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="操作人员" prop="operator">
              <el-input v-model="form.operator" placeholder="请输入操作人员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择工序状态">
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="选择开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="异常标记" prop="hasException">
          <el-switch v-model="form.hasException" />
        </el-form-item>
        <el-form-item label="异常描述" prop="exceptionDesc" v-if="form.hasException">
          <el-input v-model="form.exceptionDesc" type="textarea" placeholder="请输入异常描述" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工序详情对话框 -->
    <el-dialog title="工序详情" v-model="viewOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工序名称">{{ viewData.processName }}</el-descriptions-item>
        <el-descriptions-item label="工序类型">{{ viewData.processType }}</el-descriptions-item>
        <el-descriptions-item label="操作人员">{{ viewData.operator }}</el-descriptions-item>
        <el-descriptions-item label="工序状态">
          <el-tag :type="getProcessStatusType(viewData.status)">
            {{ getProcessStatusText(viewData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ viewData.startTime ? parseTime(viewData.startTime) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ viewData.endTime ? parseTime(viewData.endTime) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="异常标记" :span="1">
          <el-tag v-if="viewData.hasException" type="danger">异常</el-tag>
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="处理时长">{{ viewData.duration || '-' }}</el-descriptions-item>
        <el-descriptions-item label="异常描述" :span="2" v-if="viewData.hasException">
          {{ viewData.exceptionDesc || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewData.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 工序异常对话框 -->
    <el-dialog title="工序异常" v-model="exceptionOpen" width="500px" append-to-body>
      <el-form ref="exceptionForm" :model="exceptionForm" :rules="exceptionRules" label-width="100px">
        <el-form-item label="异常描述" prop="exceptionDesc">
          <el-input v-model="exceptionForm.exceptionDesc" type="textarea" placeholder="请输入异常描述" />
        </el-form-item>
        <el-form-item label="处理措施" prop="solution">
          <el-input v-model="exceptionForm.solution" type="textarea" placeholder="请输入处理措施" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitException">确 定</el-button>
          <el-button @click="exceptionOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'
import { getBatch } from '@/api/qep/production'
import { listProcessFlows, getProcessFlow, addProcessFlow, updateProcessFlow, delProcessFlow } from '@/api/qep/production'
import { listProcess } from '@/api/qep/process'

const route = useRoute()
const router = useRouter()

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = computed(() => ids.value.length !== 1)
// 非多个禁用
const multiple = computed(() => ids.value.length === 0)
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 是否显示查看弹窗
const viewOpen = ref(false)
// 是否显示异常弹窗
const exceptionOpen = ref(false)
// 工序选项
const processOptions = ref([])
// 工序流转记录表格数据
const flowList = ref([])
// 查看数据
const viewData = reactive({
  processName: '',
  processType: '',
  operator: '',
  status: '',
  startTime: '',
  endTime: '',
  hasException: false,
  exceptionDesc: '',
  duration: '',
  remark: ''
})

// 批次信息
const batchInfo = reactive({
  id: undefined,
  batchCode: '',
  productName: '',
  plannedQuantity: 0,
  status: '',
  plannedDate: '',
  actualDate: ''
})

// 状态选项
const statusOptions = [
  { value: 'PENDING', label: '待处理' },
  { value: 'IN_PROGRESS', label: '进行中' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'EXCEPTION', label: '异常' }
]

// 表单参数
const form = reactive({
  id: undefined,
  batchId: undefined,
  processId: undefined,
  processName: '',
  processType: '',
  operator: '',
  startTime: '',
  endTime: '',
  status: 'PENDING',
  hasException: false,
  exceptionDesc: '',
  remark: ''
})

// 异常表单
const exceptionForm = reactive({
  id: undefined,
  exceptionDesc: '',
  solution: '',
})

// 表单校验规则
const rules = {
  processId: [{ required: true, message: '请选择工序', trigger: 'change' }],
  operator: [{ required: true, message: '操作人员不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '工序状态不能为空', trigger: 'change' }]
}

// 异常表单校验规则
const exceptionRules = {
  exceptionDesc: [{ required: true, message: '异常描述不能为空', trigger: 'blur' }]
}

// 获取批次状态类型
const getBatchStatusType = (status) => {
  if (status === 'PLANNED') return 'info'
  if (status === 'IN_PROGRESS') return 'warning'
  if (status === 'COMPLETED') return 'success'
  if (status === 'CANCELLED') return 'danger'
  return 'info'
}

// 获取批次状态文本
const getBatchStatusText = (status) => {
  const statusMap = {
    'PLANNED': '计划中',
    'IN_PROGRESS': '生产中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 获取工序状态类型
const getProcessStatusType = (status) => {
  if (status === 'PENDING') return 'info'
  if (status === 'IN_PROGRESS') return 'warning'
  if (status === 'COMPLETED') return 'success'
  if (status === 'EXCEPTION') return 'danger'
  return 'info'
}

// 获取工序状态文本
const getProcessStatusText = (status) => {
  const statusMap = {
    'PENDING': '待处理',
    'IN_PROGRESS': '进行中',
    'COMPLETED': '已完成',
    'EXCEPTION': '异常'
  }
  return statusMap[status] || status
}

/** 查询批次信息 */
function getBatchInfo(id) {
  getBatch(id).then(response => {
    Object.assign(batchInfo, response.data)
    queryFlowList()
  })
}

/** 查询工序流转记录列表 */
function queryFlowList() {
  loading.value = true
  listProcessFlows({ batchId: batchInfo.id }).then(response => {
    flowList.value = response.rows
    loading.value = false
  })
}

/** 查询工序列表 */
function getProcessOptions() {
  listProcess().then(response => {
    processOptions.value = response.rows
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.id = undefined
  form.batchId = batchInfo.id
  form.processId = undefined
  form.processName = ''
  form.processType = ''
  form.operator = ''
  form.startTime = ''
  form.endTime = ''
  form.status = 'PENDING'
  form.hasException = false
  form.exceptionDesc = ''
  form.remark = ''
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getProcessOptions()
  open.value = true
  title.value = "添加工序流转记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  getProcessOptions()
  const id = row.id || ids.value[0]
  getProcessFlow(id).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = "修改工序流转记录"
  })
}

/** 查看按钮操作 */
function handleView(row) {
  getProcessFlow(row.id).then(response => {
    Object.assign(viewData, response.data)
    viewOpen.value = true
  })
}

/** 完成按钮操作 */
function handleComplete(row) {
  const flowData = JSON.parse(JSON.stringify(row))
  flowData.status = 'COMPLETED'
  flowData.endTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
  
  updateProcessFlow(flowData).then(response => {
    ElMessage.success("工序已完成")
    queryFlowList()
  })
}

/** 异常按钮操作 */
function handleException(row) {
  exceptionForm.id = row.id
  exceptionForm.exceptionDesc = ''
  exceptionForm.solution = ''
  exceptionOpen.value = true
}

/** 提交异常 */
function submitException() {
  // 检查必填项
  if (!exceptionForm.exceptionDesc) {
    ElMessage.warning('请输入异常描述')
    return
  }
  
  getProcessFlow(exceptionForm.id).then(response => {
    const flowData = response.data
    flowData.status = 'EXCEPTION'
    flowData.hasException = true
    flowData.exceptionDesc = exceptionForm.exceptionDesc
    flowData.remark = (flowData.remark || '') + '\n处理措施: ' + exceptionForm.solution
    
    updateProcessFlow(flowData).then(() => {
      ElMessage.success("异常记录已提交")
      exceptionOpen.value = false
      queryFlowList()
    })
  })
}

/** 工序改变事件 */
function handleProcessChange(processId) {
  const selectedProcess = processOptions.value.find(item => item.id === processId)
  if (selectedProcess) {
    form.processName = selectedProcess.name
    form.processType = selectedProcess.type
  }
}

/** 提交按钮 */
function submitForm() {
  const flowFormEl = document.querySelector('form[ref="flowForm"]')
  flowFormEl.validate(valid => {
    if (valid) {
      if (form.id !== undefined) {
        updateProcessFlow(form).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          queryFlowList()
        })
      } else {
        addProcessFlow(form).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          queryFlowList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const flowIds = row.id || ids.value
  ElMessageBox.confirm('确认删除已选中的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(function() {
    return delProcessFlow(flowIds)
  }).then(() => {
    queryFlowList()
    ElMessage.success("删除成功")
  }).catch(() => {})
}

/** 返回按钮操作 */
function goBack() {
  router.go(-1)
}

onMounted(() => {
  const batchId = route.query.batchId
  if (batchId) {
    batchInfo.id = batchId
    getBatchInfo(batchId)
    getProcessOptions()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-divider {
  margin: 20px 0;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style> 